package com.foogui.bootrabbitmq.delay;

import com.foogui.bootrabbitmq.dto.Msg;
import com.foogui.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 延迟消息生产者服务
 *
 * @author wangxin213
 * @date 2024/04/05
 */
@Service
@Slf4j
public class DelayProducerService implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendDelay5SMessage(String msg) {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(JsonUtils.toObject(msg,Msg.class).getId());
        rabbitTemplate.convertAndSend(DelayConfig.DELAY_EXCHANGE_NAME,DelayConfig.DELAY_QUEUE_5S_ROUTING_KEY, msg, correlationData);
        log.info("消息发送出去了{}", JsonUtils.toJson(msg));
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("成功发送消息到交换机了，消息id{}", correlationData.getId());
        } else {
            log.info("失败发送消息到交换机了，消息id{}", correlationData.getId());
            log.info("落库等待重新投递");
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.error("消息发送失败！returnedMessage={}",returned.getMessage());
    }
}
